﻿#include "Solution.h"
using namespace std;
#if 0
// 并查集
int Find(vector<int>& parent, int node)
{
	if (parent[node] != node)
	{
		parent[node] = Find(parent, parent[node]);
	}
	return parent[node];
}

void Union(vector<int>& parent, int node1, int node2)
{
	parent[Find(parent, node1)] = Find(parent, node2);
}

int main()
{
	// 读数据
	int n;
	cin >> n;
	vector<vector<int>> matrix(n, vector<int>(n));

	vector<int> parent(n);
	for (int i = 0; i < n; ++i)
	{
		parent[i] = i;		// 初始化并查集
		for (int j = 0; j < n; ++j)
			cin >> matrix[i][j];
	}

	vector<int> res(n, 0);
	// 遍历矩阵
	for (int i = 0; i < n; ++i)
	{
		for (int j = i; j < n; ++j)
		{
			if (matrix[i][j] > 0)
			{
				Union(parent, i, j);
				res[Find(parent, i)] += matrix[i][j];

				// Union后，子结点的父亲还没更新（也无需更新），子节点父亲存储的res不再使用，赋值到新父亲
				if (Find(parent, i) != i)
				{
					res[Find(parent, i)] += res[i];
					res[i] = 0;
				}
			}
		}
	}

	for (auto r : res)
	{
		if (r != 0)
			cout << r << " ";
	}
}
#endif

// 2个线程交替打印，控制台打印1~n
#include <semaphore>

class printNum
{
private:
	int n;
	vector<int> nums;
	binary_semaphore sEvenIdx;
	binary_semaphore sOddIdx;
public:
	printNum(int n):sEvenIdx(1),sOddIdx(0) 
	{
		this->n = n;
		nums.resize(n);
		for (int i = 0; i < n; ++i)
			nums[i] = i + 1;
	};

	void printEvenIdx()
	{
		for (int i = 0; i < n; i+=2)
		{
			sEvenIdx.acquire();
			cout << nums[i] << " ";
			sOddIdx.release();
		}
	}

	void printOddIdx()
	{
		for (int i = 1; i < n; i+=2)
		{
			sOddIdx.acquire();
			cout << nums[i] << " ";
			sEvenIdx.release();
		}
	}
};

int main()
{
	printNum pn(10);

	thread t1([&]() {pn.printEvenIdx(); });
	thread t2([&]() {pn.printOddIdx(); });

	t1.join();
	t2.join();
}